package com.iagent.register;

import com.iagent.util.Assert;
import com.iagent.util.ClassUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Alias registry
 */
public class AliasNameRegister<T> extends AbstractBeanRegister<T> {

    public AliasNameRegister(int initialCapacity) {
        super(initialCapacity);
    }

    @Override
    public <V> V getBeanByClass(String beanName, Class<V> tClass) {
        Assert.isInstanceOf(tClass, this.getBeanObject(beanName));
        return (V) this.getBeanObject(beanName);
    }

    /**
     * Registering an Alias
     *
     * @param beanName
     * @param target
     */
    public void registerAlias(String beanName, T target) {
        this.registerBean(beanName, target);
    }

    /**
     * Get the value corresponding to the alias
     *
     * @param beanName
     * @return
     */
    public T getAlias(String beanName) {
        return this.getBeanObject(beanName);
    }

    /**
     * Gets the Class collection of the specified Class and its subclasses
     *
     * @param vClass
     * @param <V>
     * @return
     */
    public <V> List<Class<V>> getAliasClassListByClass(Class<V> vClass) {
        List<Class<V>> resultList = new ArrayList<>(16);
        for (String key : getAllBeanNames()) {
            T alias = this.getAlias(key);
            if (alias instanceof Class &&
                    vClass.isAssignableFrom((Class<?>) alias)) {
                resultList.add((Class<V>) alias);
            }
        }
        return resultList;
    }

    /**
     * Contains the specified data
     *
     * @param vClass
     * @param <V>
     * @return
     */
    public <V> boolean containsValue(Class<V> vClass) {
        for (String key : getAllBeanNames()) {
            T alias = this.getAlias(key);
            if (alias instanceof Class && ClassUtils.isEqualsClass(vClass, (Class) alias)) {
                return true;
            }
        }
        return false;
    }

}
